package com.drinks.yiniang.ui.fragment.user.friends;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.user.friends.FriendsListAdapter;
import com.drinks.yiniang.common.recycler.decoration.FirstItemDecoration;
import com.drinks.yiniang.entity.event.CommunityFollowEvent;
import com.drinks.yiniang.entity.user.friends.FriendsJson;
import com.drinks.yiniang.io.api.CommunityApiIO;
import com.drinks.yiniang.io.api.UserApiIO;
import com.drinks.yiniang.ui.activity.community.UserCommunityActivity;
import com.drinks.yiniang.ui.activity.conversation.ServiceChatActivity;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.hansen.library.ui.widget.refresh.MSwipeRefreshLayout;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.entity.BaseJson;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.ui.fragment.BaseLazyFragment;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

/**
 * 好友列表
 *
 * @author han
 * @date 2019/09/08
 * A simple {@link Fragment} subclass.
 */
public class FriendsListFragment extends BaseLazyFragment implements SwipeRefreshLayout.OnRefreshListener,
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.RequestLoadMoreListener {

    //refresh
    private MSwipeRefreshLayout refresh_friends_list;
    //列表
    private BaseRecyclerView rcv_friends_list;

    private FriendsListAdapter mFriendsListAdapter;

    //默认关注的列表
    private String mFriendsType = Constants.TYPE_FRIENDS_FOLLOW;

    private int mPages;

    public FriendsListFragment() {
        // Required empty public constructor
    }

    public static FriendsListFragment newInstance(String type) {
        Bundle bundle = new Bundle();
        bundle.putString(Constants.KeyType, type);

        FriendsListFragment fragment = new FriendsListFragment();
        fragment.setArguments(bundle);

        return fragment;
    }

    @Override
    protected int getResID() {
        return R.layout.fragment_friends_list;
    }

    @Override
    protected void initView(View mView) {
        refresh_friends_list = mView.findViewById(R.id.refresh_friends_list);

        rcv_friends_list = mView.findViewById(R.id.rcv_friends_list);
    }

    @Override
    protected void initData() {
        mContext = getActivity();

        if (getArguments() != null) {
            mFriendsType = getArguments().getString(Constants.KeyType, Constants.TYPE_FRIENDS_FOLLOW);
        }

        initAdapter();
    }

    private void initAdapter() {
        rcv_friends_list.setLayoutManager(new LinearLayoutManager(mContext));
        rcv_friends_list.addItemDecoration(FirstItemDecoration.getItemDPDecoration(10));

        mFriendsListAdapter = new FriendsListAdapter(mContext, new ArrayList<FriendsJson.FriendsList>());
        mFriendsListAdapter.setCenterEmpty(getLayoutInflater(), rcv_friends_list);
        mFriendsListAdapter.bindToRecyclerView(rcv_friends_list);
        mFriendsListAdapter.setFriendsType(mFriendsType);
    }

    @Override
    protected void listener() {
        refresh_friends_list.setOnRefreshListener(this);

        mFriendsListAdapter.setOnItemClickListener(this);
        mFriendsListAdapter.setOnItemChildClickListener(this);
        mFriendsListAdapter.setOnLoadMoreListener(this, rcv_friends_list);
    }

    @Override
    protected void widgetClick(View v) {

    }

    @Override
    protected void lazyLoadData() {
        getFriendsList();
    }

    @Override
    public void onRefresh() {
        getFriendsList();
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        FriendsJson.FriendsList data = mFriendsListAdapter.getItem(position);

        if(data == null) {
            return;
        }

        switch (view.getId()) {
            case R.id.tv_friends_ls_follow://关注状态
                if(Constants.TYPE_FRIENDS_FANS.equals(mFriendsType)) {//我的粉丝页面，点击关注粉丝
                    doFollow(data.getFans_id(), data.getStatus());
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        FriendsJson.FriendsList data = mFriendsListAdapter.getItem(position);

        if(data == null) {
            return;
        }

        Intent intent = new Intent(mContext, UserCommunityActivity.class);
        intent.putExtra(Constants.KeyUserId, Constants.TYPE_FRIENDS_FOLLOW.equals(mFriendsType) ? data.getFocus_fans_id() : data.getFans_id());
        startActivity(intent);
    }

    @Override
    public void onLoadMoreRequested() {
        UserApiIO.getInstance().getFriendsList(mFriendsType, mPages, new APIRequestCallback<FriendsJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(FriendsJson res) {
                if (mFriendsListAdapter == null) {
                    return;
                }

                mPages++;

                mFriendsListAdapter.addData(res.getData().getData());

                if (CommonUtils.isHasMoreData(res.getData().getData())) {
                    mFriendsListAdapter.loadMoreComplete();
                } else {
                    mFriendsListAdapter.loadMoreEnd();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mFriendsListAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    //关注或取消关注
    private void doFollow(String userId, String status) {
        if(StringUtils.isEmpty(userId)) {
            ToastUtils.showShort(R.string.text_user_not_exist);
            return;
        }

        //状态 1关注我 2相互关注
        if("2".equals(status)) {
            //doUnFollow(userId);
            return;
        }

        showLoadingDialog();

        //执行关注
        CommunityApiIO.getInstance().doCommunityFollow(userId, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(BaseJson res) {
                //更关注列表
                EventBus.getDefault().post(new CommunityFollowEvent());
                //setFollowStatus(Constants.STATUS_ALREADY_FOLLOW);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    //取消关注
    private void doUnFollow(String userId) {
        showLoadingDialog();

        CommunityApiIO.getInstance().doCommunityFollowCancel(userId, new APIRequestCallback<BaseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(BaseJson res) {
                //更关注列表
                EventBus.getDefault().post(new CommunityFollowEvent());
                //setFollowStatus(Constants.STATUS_UN_FOLLOW);
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    private void getFriendsList() {
        if (!refresh_friends_list.isRefreshing()) {
            showLoadingDialog();
        }

        mPages = 1;

        UserApiIO.getInstance().getFriendsList(mFriendsType, mPages, new APIRequestCallback<FriendsJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(FriendsJson res) {
                if (mFriendsListAdapter == null) {
                    return;
                }

                mPages++;

                mFriendsListAdapter.getData().clear();
                mFriendsListAdapter.addData(res.getData().getData());

                if (CommonUtils.isHasMoreData(res.getData().getData())) {
                    mFriendsListAdapter.loadMoreComplete();
                } else {
                    mFriendsListAdapter.loadMoreEnd();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
                mFriendsListAdapter.loadMoreFail();
            }

            @Override
            public void onComplete() {
                refresh_friends_list.setRefreshing(false);
                dismissDialog();
            }
        });
    }
}
